<?php

namespace app\api\model;

use app\admin\event\SystemLog;
use app\admin\model\Admin;
use think\db\Query;
use think\exception\DbException;
use think\Model;
use think\Db;

class Warehouse extends Base
{

    protected static function init()
    {
        self::observe(SystemLog::class);
    }

    protected $prefix = 'jxc';
    protected $pk = 'id';
    protected $table = 'jxc_warehouse';

    // 定义全局的查询范围
    public function scopeMaker($query)
    {
        $c = Admin::find(\app\http\GetUid::getUId());
        // 门店负责人可查看自己门店的所有信息
        if ($c->level == 2) {
            $maker = Admin::where('store', $c->store)->where('level', 3)->column('id');
        } elseif ($c->level == 1) {
            $maker = Admin::column('id');
        } else {
            $maker = $c->id;
        }
        $query->whereIn('maker', $maker);
    }
    /**
     * @return \think\model\relation\BelongsToMany
     */
    public function goods()
    {
        return $this->belongsToMany(Goods::class, WarehouseGoods::class);
    }

    public function searchNameAttr(Query $query, $value, $data)
    {
        $query->whereLike('name', "%" . $value . "%");
    }

    /*public function getStatusAttr($value)
    {
        $status = [1=>'禁用',2=>'启用'];
        return $status[$value];
    }*/

    /*protected function getPersonAttr($value, $data)
    {
        return Db::name('keeper')->where('id', $value['person'])->value('name');
    }*/

    /**
     * @param string $name
     * @param string $status
     * @param int $page
     * @param int $size
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($name = '', $status = '', $page = 1, $size = 10)
    {
        $where = [];
        if (!empty($name)) {
            $where[] = ['name','like', "%" . $name . "%"];
        }
        if (!empty($status)) {
            $where[] = ['status','=', $status];
        }
        $list = $this->scope('maker')->where($where)->order('sort asc')->page($page, $size)->paginate($size);
        $list =$list->toArray();
        foreach ($list['data'] as $k=>$v)
        {
            $list['data'][$k]['create_time'] =date('Y-m-d',$v['create_time']);
            $list['data'][$k]['edit_time'] =isset($v['edit_time']) ? date('Y-m-d H:i:s',$v['edit_time']) : '';
            $list['data'][$k]['person'] =$this->getValue('keeper',['id'=>$v['person']],'name');
            $list['data'][$k]['store'] =$this->getValue('store',['id'=>$v['store']],'name');
            switch ($v['status']){
                case 1:
                    $list['data'][$k]['status1'] ='禁用';
                    break;
                default:
                    $list['data'][$k]['status1'] ='启用';
            }
        }
        return $list;
    }

    public function getAll()
    {
        return $this->scope('maker')->field('id,name')->where('status',2)->order('id asc')->select();
    }

    /**
     * @param $data
     * @return Warehouse
     */
    public function getWarehouseAdd($data)
    {
        return $this::create($data);
    }

    public function getPerson()
    {
        return $this->select();
    }

    /**
     * @param $id
     * @return array|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInfo($id)
    {
        $list =$this->findOrFail($id)->toArray();
        $list['store_name'] =$this->getValue('store',['id'=>$list['store']],'name');
        return $list;
    }

    /**
     * @param $id
     * @return array|\PDOStatement|string|Model
     */
    public function getWarehouseEdit($id, $data)
    {
        return $this->getEdit('warehouse',['id'=>$id],$data);
    }

    /**
     * @param $id
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function getWarehouseDel($id)
    {
        return $this->getDel('warehouse',$id);
    }

    /**
     * 生产入库单 列表
     * @return json
     */
    public function getProductionList($data,$field = "", $order = "id desc")
    {
        $where = [];
        if (!empty($data['status'])) {
            $where[] = ['status','=',$data['status']];
        }
        if($data['start_time'] && $data['end_time']){
            $where[] =['create_time','between',[$data['start_time'],$data['end_time']]];
        }
        if (!empty($data['warehouse'])) {
            $where[] = ['warehouse','=',$data['warehouse']];
        }
        if (!empty($data['keeper'])) {
            $where[] = ['keeper','=',$data['keeper']];
        }
        if (!empty($data['number'])) {
            $where[] = ['number','like', "%" . $data['number'] . "%"];
        }
        $list =$this->getPage('production','id,status,number,create_time,warehouse,keeper,des',$where,'id desc',$data['page'],$data['size']);
        $list =$list->toArray();
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['create_time'] =date('Y-m-d',$v['create_time']);
            $list['data'][$k]['keeper'] =$this->getValue('keeper',['id'=>$v['keeper']],'name');
            $list['data'][$k]['warehouse'] =$this->getValue('warehouse',['id'=>$v['warehouse']],'name');
            switch ($v['status']){
                case 1:
                    $list['data'][$k]['status'] ='草稿';
                    $list['data'][$k]['status2'] =20;
                    break;
                case 2:
                    $list['data'][$k]['status'] ='已入库';
                    $list['data'][$k]['status2'] =17;
                    break;
                case 3:
                    $list['data'][$k]['status'] ='已撤销';
                    $list['data'][$k]['status2'] =19;
                    break;
                default:
                    $list['data'][$k]['status'] ='待入库';
                    $list['data'][$k]['status2'] =18;
            }
        }
        return $list;
    }

    public function getproductionAdd($data)
    {
        $list =$this->getAdd('production',$data);
        if($data['status'] ==4){
            foreach($data['goods'] as $k=>$v){
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
                if(empty($stockInfo)){
                    $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                    $rel1 =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $v['warehouse'],
                        'put_in' => $v['put_number']
                    ];
                    $this->getAdd('product_stock', $rel1);
                }else{
                   $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'put_in',$v['put_number']);
                }
                $rel['product_id'] =$v['product_id'];
                $rel['put_number'] =isset($v['put_number']) ? $v['put_number'] : 0;
                $rel['front_stock'] =isset($stockInfo['stock']) ? $stockInfo['stock'] : 0;
                $rel['pid'] =$list;
                $rel['instock'] =$rel['front_stock'] + $v['put_number'];
                $this->getAdd('production_relation',$rel);
            }
            $stor['status'] =1;
            $stor['number'] =$data['number'];
            $stor['create_time'] =$data['create_time'];
            $stor['warehouse'] =$data['warehouse'];
            $stor['maker'] =$data['maker'];
            $stor['type'] =2;
            $stor['des'] =$data['des'];
            $stor['relation_id'] =$list;
            $this->getAdd('instock',$stor);
        }else{
            foreach($data['goods'] as $k=>$v){
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
                if(empty($stockInfo)){
                    $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                    $rel1 =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'stock' => 0
                    ];
                    $this->getAdd('product_stock', $rel1);
                }
                $rel['product_id'] =$v['product_id'];
                $rel['put_number'] =isset($v['put_number']) ? $v['put_number'] : 0;
                $rel['front_stock'] =isset($stockInfo['stock']) ? $stockInfo['stock'] : 0;
                $rel['pid'] =$list;
                $rel['instock'] = $rel['front_stock'] + $v['put_number'];
                $this->getAdd('production_relation',$rel);
            }
        }
        return $list;
    }

    public function getProductionDetail($id)
    {
        $list =$this->getOne('production','id,status,number,warehouse,keeper,create_time,des',['id'=>$id]);
        $list['goods'] =$this->getselectList('production_relation','*',['pid'=>$list['id']]);
        foreach($list['goods'] as $k=>$v){
            $dan =$this->getOne('product','commodity_id,color,size',['id'=>$v['product_id']]);
            $goods =$this->getOne('commodity','name,item,goods_code,unit,trade_price',['id'=>$dan['commodity_id']]);
            $list['goods'][$k]['commodity_id'] =$dan['commodity_id'];
            $list['goods'][$k]['name'] =$goods['name'];
            $list['goods'][$k]['item'] =$goods['item'];
            $list['goods'][$k]['goods_code'] =$goods['goods_code'];
            $list['goods'][$k]['color'] =$this->getValue('color3',['id'=>$dan['color']],'name');
            $list['goods'][$k]['size'] =$this->getValue('color3',['id'=>$dan['size']],'name');
            $list['goods'][$k]['unit'] =$this->getValue('color1',['id'=>$goods['unit']],'name');
            $list['goods'][$k]['price'] =$goods['trade_price'];
        }
        $list['keeper_name'] =$this->getValue('keeper',['id'=>$list['keeper']],'name');
        $list['warehouse_name'] =$this->getValue('warehouse',['id'=>$list['warehouse']],'name');
        $list['create_time'] = date('Y-m-d', $list['create_time']);
        switch ($list['status']){
            case 1:
                $list['status'] ='草稿';
                break;
            case 2:
                $list['status'] ='已入库';
                break;
            case 3:
                $list['status'] ='已撤销';
                break;
            default:
                $list['status'] ='待入库';
        }
        return $list;
    }

    public function getProductionRevoke($id)
    {
        try{
            $list =$this->getOne('production','*',['id'=>$id]);
            if(in_array($list['status'],[2,3])){
                throw new \Exception('单据无法撤销');
            }else{
                $this->getSetField('instock',array('relation_id'=>$id,'type'=>2),['status'=>4]);
                return $this->getSetField('production',['id'=>$id],['status'=>3]);
            }
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getProductionDel($id)
    {
        try{
            $list =$this->getOne('production','*',['id'=>$id]);
            if(in_array($list['status'],[2,3])){
                throw new \Exception('单据已入库,无法删除');
            }else{
                if($list['status'] ==4){
                    Db::name('instock')->where(['type'=>2,'relation_id'=>$id])->delete();
                }
                Db::name('production_relation')->whereIn('pid',$id)->delete();
                return $this->getDel('production',$id);
            }
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getPutStock($id,$data)
    {
        $this->getEdit('production',['id'=>$id],$data);
        Db::name('production_relation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k=>$v){
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
            if(empty($stockInfo)){
                $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                $rel =[
                    'commodity_id' => $commodity_id,
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['warehouse'],
                    'put_in' => $v['put_number']
                ];
                $this->getAdd('product_stock', $rel);
            }
            $rel['product_id'] =$v['product_id'];
            $rel['put_number'] =isset($v['put_number']) ? $v['put_number'] : 0;
            $rel['front_stock'] =isset($stockInfo['stock']) ? $stockInfo['stock'] : 0;
            $rel['pid'] =$id;
            $rel['instock'] = $rel['front_stock'] + $v['put_number'];
            $this->getAdd('production_relation',$rel);
            $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'put_in',$v['put_number']);
        }
        $list =$this->getOne('purchase','*',['id'=>$id]);
        $stock['status'] =1;
        $stock['number'] =$list['number'];
        $stock['create_time'] =$list['create_time'];
        $stock['warehouse'] =$list['warehouse'];
        $stock['maker'] =$list['maker'];
        $stock['type'] =2;//单据类型 1采购单 2生产入库单 3调拨单 4销售退货单  5配货退货单
        $stock['des'] =$list['des'];
        $stock['relation_id'] =$id;
        return $this->getAdd('instock',$stock);
    }

    public function getProductionDraft($id,$data)
    {
        $list = $this->getEdit('production',['id'=>$id],$data);
        Db::name('production_relation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k=>$v){
            $stock =$this->getValue('product_stock',['product_id'=>$v['product_id']],'stock');
            $rel['product_id'] =$v['product_id'];
            $rel['put_number'] =isset($v['put_number']) ? $v['put_number'] : 0;
            $rel['front_stock'] =isset($stock) ? $stock : 0;
            $rel['pid'] =$id;
            $rel['instock'] = $rel['front_stock'] + $v['put_number'];
            $this->getAdd('production_relation',$rel);
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
            if(empty($stockInfo)){
                $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                $rel1 =[
                    'commodity_id' => $commodity_id,
                    'product_id' => $v['product_id'],
                    'stock' => 0
                ];
                $this->getAdd('product_stock', $rel1);
            }
        }
        return $list;
    }

    public function getProductionDepot($id)
    {
        $list = $this->getOne('production','*',['id'=>$id]);
        $list['goods'] = $this->getselectList('production_relation','*',['pid'=>$list['id']]);
        foreach($list['goods'] as $k=>$v){
            $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$list['warehouse']],'stock',$v['put_number']);
            $this->getSetDec('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$list['warehouse']],'put_in',$v['put_number']);
            $stock =$this->getValue('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$list['warehouse']],'stock');
            $flow =[
                'goods_id' =>$v['product_id'],
                'create_time' =>time(),
                'warehouse' =>$list['warehouse'],
                'type' =>'生产入库单',
                'number' =>$list['number'],
                'add_num' =>$v['put_number'],
                'sur_num' =>$stock + $v['put_number']
            ];
            $this->getAdd('flowing_water',$flow);
        }
            //全部入库
            $this->getSetField('production',['id'=>$id],['status'=>2]);
            $this->getSetField('instock',['relation_id'=>$id,'type'=>2],['status'=>3]);
        return 1;
    }

    public function getAllotList($data,$field = "", $order = "create_time desc")
    {
        $where = [];
        if (!empty($data['status'])) {
            $where[] = ['status','=',$data['status']];
        }
        if($data['start_time'] && $data['end_time']){
            $where[] =['create_time','between',[$data['start_time'],$data['end_time']]];
        }
        if (!empty($data['call_out'])) {
            $where[] = ['call_out','=',$data['call_out']];
        }
        if (!empty($data['call_in'])) {
            $where[] = ['call_in','=',$data['call_in']];
        }
        if (!empty($data['number'])) {
            $where[] = ['number','like', "%" . $data['number'] . "%"];
        }
        if (!empty($data['maker'])) {
            $where[] = ['maker','=',$data['maker']];
        }
        $list =$this->getPage('allot','id,status,number,create_time,call_in,call_out,maker,des',$where,'id desc',$data['page'],$data['size']);
        $list =$list->toArray();
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['create_time'] =date('Y-m-d',$v['create_time']);
            $list['data'][$k]['call_in'] =$this->getValue('warehouse',['id'=>$v['call_in']],'name');
            $list['data'][$k]['call_out'] =$this->getValue('warehouse',['id'=>$v['call_out']],'name');
            $list['data'][$k]['maker'] =$this->getValue('admin',['id'=>$v['maker']],'name');
            switch ($v['status']){
                case 1:
                    $list['data'][$k]['status'] ='草稿';
                    $list['data'][$k]['status2'] =26;
                    break;
                case 2:
                    $list['data'][$k]['status'] ='已调拨';
                    $list['data'][$k]['status2'] =24;
                    break;
                default:
                    $list['data'][$k]['status'] ='已撤销';
                    $list['data'][$k]['status2'] =25;
            }
        }
        return $list;
    }
    /**
     * 调拨单 新增
     * @param $data
     * @return int|string
     */
    public function getAllotAdd($data)
    {
        $arr =$this->getAdd('allot',$data);
        if($data['status'] ==2){
            $stock['status'] =3;
            $stock['number'] = $data['number'];
            $stock['create_time'] =$data['create_time'];
            $stock['warehouse'] =$data['call_out'];
            $stock['maker'] =$data['maker'];
            $stock['type'] =3;//单据类型 1销售单 2配货单 3调拨单
            $stock['des'] =$data['des'];
            $stock['relation_id'] =$arr;
            $this->getAdd('outstock',$stock);
            $put['status'] =2;
            $put['number'] = $data['number'];
            $put['create_time'] =$data['create_time'];
            $put['warehouse'] =$data['call_in'];
            $put['maker'] =$data['maker'];
            $put['type'] =3;//单据类型 1采购单 2生产入库单 3调拨单
            $put['des'] =$data['des'];
            $put['relation_id'] =$arr;
            $this->getAdd('instock',$put);
            foreach($data['goods'] as $k=>$v){
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['call_in']]);
                $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                if(empty($stockInfo)){
                    $rel =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['call_in'],
                        'stock' =>$v['put_number']
                    ];
                    $this->getAdd('product_stock', $rel);
                }else{
                    $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['call_in']],'stock',$v['put_number']);
                }
                $stockInfo2 =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['call_out']]);
                if(empty($stockInfo2)){
                    $rel2 =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['call_out'],
                        'stock' =>$v['put_number']
                    ];
                    $this->getAdd('product_stock', $rel2);
                }else{
                    $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['call_out']],'stock',$v['put_number']);
                }
                $callIn['product_id'] = $v['product_id'];
                $callIn['put_number'] = $v['put_number'];
                $callIn['call_in_total'] = $this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$data['call_in']], 'stock');
                $callIn['call_out_total'] =$this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$data['call_out']], 'stock');
                $callIn['pid'] = $arr;
                $this->getAdd('allotrelation',$callIn);
                $flow =[
                    'goods_id' =>$v['product_id'],
                    'create_time' =>time(),
                    'warehouse' =>$data['call_in'],
                    'type' =>'调拨单',
                    'number' =>$data['number'],
                    'add_num' =>$v['put_number'],
                    'sur_num' =>$callIn['call_in_total'] + $v['put_number']
                ];
                $this->getAdd('flowing_water',$flow);
                $flow2 =[
                    'goods_id' =>$v['product_id'],
                    'create_time' =>time(),
                    'warehouse' =>$data['call_out'],
                    'type' =>'调拨单',
                    'number' =>$data['number'],
                    'add_num' =>'-'.$v['put_number'],
                    'sur_num' =>$callIn['call_out_total'] - $v['put_number']
                ];
                $this->getAdd('flowing_water',$flow2);
            }
        }else{
            foreach($data['goods'] as $k=>$v){
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['call_in']]);
                $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                if(empty($stockInfo)){
                    $rel =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['call_in'],
                        'stock' => 0
                    ];
                    $this->getAdd('product_stock', $rel);
                }
                $stockInfo2 =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['call_out']]);
                if(empty($stockInfo2)){
                    $rel2 =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['call_out'],
                        'stock' => 0
                    ];
                    $this->getAdd('product_stock', $rel2);
                }
                $callIn['product_id'] = $v['product_id'];
                $callIn['put_number'] = $v['put_number'];
                $callIn['call_in_total'] = $this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$data['call_in']], 'stock');
                $callIn['call_out_total'] =$this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$data['call_out']], 'stock');
                $callIn['pid'] = $arr;
                $this->getAdd('allotrelation',$callIn);
            }
        }
        return $arr;
    }

    public function getAllotDraft($id,$data)
    {
        $list = $this->getEdit('allot',['id'=>$id],$data);
        Db::name('allotrelation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k=>$v){
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['call_in']]);
            $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
            if(empty($stockInfo)){
                $rel =[
                    'commodity_id' => $commodity_id,
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['call_in'],
                    'stock' => 0
                ];
                $this->getAdd('product_stock', $rel);
            }
            $stockInfo2 =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['call_out']]);
            if(empty($stockInfo2)){
                $rel2 =[
                    'commodity_id' => $commodity_id,
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['call_out'],
                    'stock' => 0
                ];
                $this->getAdd('product_stock', $rel2);
            }
            $callIn['product_id'] = $v['product_id'];
            $callIn['put_number'] = $v['put_number'];
            $callIn['call_in_total'] = $this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$data['call_in']], 'stock');
            $callIn['call_out_total'] =$this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$data['call_out']], 'stock');
            $callIn['pid'] =$id;
            $this->getAdd('allotrelation',$callIn);
        }
        return $list;
    }

    /**
     * 调拨单 查找
     * @param $id
     * @return array|\PDOStatement|string|Model|null
     */
    public function getAllotInfo($id)
    {
        $list =$this->getOne('allot','*',['id'=>$id]);
        $list['goods'] =$this->getselectList('allotrelation','*',['pid'=>$id]);
        foreach($list['goods'] as $k=>$v){
            $dan =$this->getOne('product','commodity_id,color,size',['id'=>$v['product_id']]);
            $goods =$this->getOne('commodity','name,item,goods_code,unit,trade_price',['id'=>$dan['commodity_id']]);
            $list['goods'][$k]['commodity_id'] =$dan['commodity_id'];
            $list['goods'][$k]['name'] =$goods['name'];
            $list['goods'][$k]['item'] =$goods['item'];
            $list['goods'][$k]['goods_code'] =$goods['goods_code'];
            $list['goods'][$k]['color'] =$this->getValue('color3',['id'=>$dan['color']],'name');
            $list['goods'][$k]['size'] =$this->getValue('color3',['id'=>$dan['size']],'name');
            $list['goods'][$k]['unit'] =$this->getValue('color1',['id'=>$goods['unit']],'name');
            $list['goods'][$k]['price'] =$goods['trade_price'];
        }
        $list['maker_name'] =$this->getValue('admin',['id'=>$list['maker']],'name');
        $list['call_in_name'] =$this->getValue('warehouse',['id'=>$list['call_in']],'name');
        $list['call_out_name'] =$this->getValue('warehouse',['id'=>$list['call_out']],'name');
        $list['create_time'] = date('Y-m-d', $list['create_time']);
        switch ($list['status']){
            case 1:
                $list['status'] ='草稿';
                break;
            case 2:
                $list['status'] ='已调拨';
                break;
            default:
                $list['status'] ='已撤销';
        }
        return $list;
    }

    /**
     * 调拨单 调拨
     * @param $id
     * @return int
     */
    public function getAllot($id,$data)
    {
        $this->getEdit('allot',['id'=>$id],$data);
        Db::name('allotrelation')->whereIn('pid',$id)->delete();
        $list =$this->getOne('allot','*',['id'=>$id]);
        foreach ($data['goods'] as $k=>$v){
            $callIn['product_id'] = $v['product_id'];
            $callIn['put_number'] = $v['put_number'];
            $callIn['pid'] =$id;
            $callIn['call_in_total'] = $this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$data['call_in']], 'stock');
            $callIn['call_out_total'] =$this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$data['call_out']], 'stock');
            $this->getAdd('allotrelation',$callIn);
            $this->getSetInc('product_stock',['warehouse'=>$data['call_in'],'product_id'=>$v['product_id']],'stock',$v['put_number']);
            $flow1 =[
                'goods_id' =>$v['product_id'],
                'create_time' =>time(),
                'warehouse' =>$data['call_in'],
                'type' =>'调拨单',
                'number' =>$list['number'],
                'add_num' =>$v['put_number'],
                'sur_num' =>$callIn['call_in_total']
            ];
            $this->getAdd('flowing_water',$flow1);
            $this->getSetDec('product_stock',['warehouse'=>$data['call_out'],'product_id'=>$v['product_id']],'stock',$v['put_number']);
            $flow2 =[
                'goods_id' =>$v['product_id'],
                'create_time' =>time(),
                'warehouse' =>$data['call_out'],
                'type' =>'调拨单',
                'number' =>$list['number'],
                'add_num' =>'-'.$v['put_number'],
                'sur_num' =>$callIn['call_out_total']
            ];
            $this->getAdd('flowing_water',$flow2);
        }
        $this->getSetField('outstock',array('relation_id'=>$id,'type'=>3),['status'=>3]);
        $this->getSetField('instock',array('relation_id'=>$id,'type'=>3),['status'=>3]);
        return 1;
    }

    /**
     * 调拨单 撤销
     * @param $id
     * @return int
     */
    public function getAllotRevoke($id)
    {
        try{
            $list =$this->getOne('allot','*',['id'=>$id]);
            if(in_array($list['status'],[2,3])){
                throw new \Exception('单据已调拨,无法撤销');
            }else{
                return $this->getSetField('allot',['id'=>$id],['status'=>3]);
            }
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * 调拨单 删除
     * @param $id
     * @return int
     */
    public function getAllotDel($id)
    {
        try{
            $list =$this->getOne('allot','*',['id'=>$id]);
            if(in_array($list['status'],[2,3])){
                throw new \Exception('单据已调拨,无法删除');
            }else{
                Db::name('allotrelation')->whereIn('pid',$id)->delete();
                return $this->getDel('allot',$id);
            }
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getInventoryList($data,$field='',$order = "id desc")
    {
        $where = [];
        if (!empty($data['status'])) {
            $where[] = ['status','=',$data['status']];
        }
        if($data['start_time'] && $data['end_time']){
            $where[] =['create_time','between time',[$data['start_time'],$data['end_time']]];
        }
        if (!empty($data['warehouse'])) {
            $where[] = ['warehouse','=',$data['warehouse']];
        }
        if (!empty($data['number'])) {
            $where[] = ['number','like', "%" . $data['number'] . "%"];
        }
        $list =$this->getPage('inventory','*',$where,'id desc',$data['page'],$data['size']);
        $list =$list->toArray();
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['create_time'] =date('Y-m-d',$v['create_time']);
            $list['data'][$k]['warehouse'] =$this->getValue('warehouse',['id'=>$v['warehouse']],'name');
            $list['data'][$k]['maker'] =$this->getValue('admin',['id'=>$v['maker']],'name');
            $rel =Db::name('inventory_relation')->where('pid',$v['id'])->column('put_number');
            $list['data'][$k]['total'] =array_sum($rel);
            switch ($v['status']){
                case 1:
                    $list['data'][$k]['status'] ='已盘点';
                    $list['data'][$k]['status2'] =21;
                    break;
                case 2:
                    $list['data'][$k]['status'] ='已撤销';
                    $list['data'][$k]['status2'] =22;
                    break;
                default:
                    $list['data'][$k]['status'] ='草稿';
                    $list['data'][$k]['status2'] =23;
            }
        }
        return $list;
    }

    public function getInventoryAdd($data)
    {
        $arr =$this->getAdd('inventory',$data);
        if($data['status'] ==1) {
            foreach ($data['goods'] as $k => $v) {
                $dan = $this->getValue('product', ['id' => $v['product_id']], 'commodity_id');
                $current = $this->getValue('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$data['warehouse']], 'stock');
                $price = $this->getValue('commodity', ['id' => $dan], 'purchase_price');
                $rel['product_id'] = $v['product_id'];
                $rel['pid'] = $arr;
                $rel['put_number'] = $v['put_number'];
                $rel['front'] =$current;
                if ($current - $v['put_number'] > 0) {
                    $rel['loss_num'] = $current - $v['put_number'];
                    $rel['loss_price'] = $rel['loss_num'] * $price;
                    $rel['state'] = '盘盈';
                } else if ($current - $v['put_number'] == 0) {
                    $rel['loss_num'] = 0;
                    $rel['loss_price'] = 0.00;
                    $rel['state'] = '正常';
                } else {
                    $rel['loss_num'] = '-' . $v['put_number'] - $current;
                    $rel['loss_price'] = '-' . $rel['loss_num'] * $price;
                    $rel['state'] = '盘亏';
                }
                $this->getAdd('inventory_relation', $rel);
            }
        }else{
            foreach ($data['goods'] as $k => $v) {
                $rel['product_id'] = $v['product_id'];
                $rel['pid'] = $arr;
                $rel['put_number'] = $v['put_number'];
                $this->getAdd('inventory_relation', $rel);
            }
        }
        return $arr;
    }

    public function getInventoryDetailed($data)
    {
        $where = [];
        if (isset($data['maker'])) {
            $where[] = ['i.maker','=',$data['maker']];
        }
        if (isset($data['goods'])) {
            $where[] = ['com.id','=',$data['goods']];
        }
        if (isset($data['color'])) {
            $where[] = ['p.color','=',$data['color']];
        }
        if (isset($data['sizes'])) {
            $where[] = ['p.size','=',$data['sizes']];
        }
        if (isset($data['num']) && $data['num'] === 'true') {
            $where[] = ['r.put_number','=',0];
        }
        $list =Db::name('inventory')->alias('i')
            ->leftJoin('inventory_relation r','r.pid = i.id')
            ->leftJoin('product p','p.id = r.product_id')
            ->leftJoin('commodity com','com.id = p.commodity_id')
            ->leftJoin('color1 c1','c1.id = com.unit')
            ->leftJoin('color3 c2','c2.id = p.color')
            ->leftJoin('color3 c3','c3.id = p.size')
            ->field('r.put_number,front,com.name,item,goods_code,unit,p.color,size,c1.name as unit,c2.name as color,c3.name as size')
            ->where($where)->page($data['page'],$data['size'])->paginate($data['size']);
        return $list;
    }

    public function getInventoryInfo($id)
    {
        $list = $this->getOne('inventory','*',['id'=>$id]);
        $list['goods'] = $this->getselectList('inventory_relation','*',['pid'=>$list['id']]);
        $num =[];
        $loss_num =[];
        $loss_price =[];
        foreach($list['goods'] as $k=>$v){
            $dan =$this->getOne('product','commodity_id,color,size',['id'=>$v['product_id']]);
            $goods =$this->getOne('commodity','name,item,goods_code,unit,purchase_price',['id'=>$dan['commodity_id']]);
            $list['goods'][$k]['commodity_id'] =$dan['commodity_id'];
            $list['goods'][$k]['name'] =$goods['name'];
            $list['goods'][$k]['item'] =$goods['item'];
            $list['goods'][$k]['goods_code'] =$goods['goods_code'];
            $list['goods'][$k]['color'] =$this->getValue('color3',['id'=>$dan['color']],'name');
            $list['goods'][$k]['size'] =$this->getValue('color3',['id'=>$dan['size']],'name');
            $list['goods'][$k]['unit'] =$this->getValue('color1',['id'=>$goods['unit']],'name');
            $list['goods'][$k]['price'] =$goods['purchase_price'];
            $num[] =$v['put_number'];
            $loss_num[] =$v['loss_num'];
            $loss_price[] =$v['loss_price'];
        }
        $list['create_time'] =date('Y-m-d',$list['create_time']);
        $list['maker_name'] =$this->getValue('admin',['id'=>$list['maker']],'name');
        $list['warehouse_name'] =$this->getValue('warehouse',['id'=>$list['warehouse']],'name');
        $list['num'] =array_sum($num);
        $list['loss_num'] =array_sum($loss_num);
        $list['loss_price'] =array_sum($loss_price);
        return $list;
    }

    public function getInventoryDel($id)
    {
        try{
            Db::name('inventory_relation')->whereIn('pid',$id)->delete();
            return $this->getDel('inventory',$id);
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getInventoryRevoke($id)
    {
        try{
            return $this->getSetField('inventory',['id'=>$id],['status'=>2]);
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getInventoryDraft($id,$data)
    {
        $list = $this->getEdit('inventory',['id'=>$id],$data);
        Db::name('inventory_relation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k=>$v){
            $rel['product_id'] = $v['product_id'];
            $rel['pid'] = $id;
            $rel['put_number'] = $v['put_number'];
            $this->getAdd('inventory_relation',$rel);
        }
        return $list;
    }

    public function getInventory($id,$data)
    {
        $this->getEdit('inventory',['id'=>$id],$data);
        Db::name('inventory_relation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k=>$v){
            $dan = $this->getValue('product', ['id' => $v['product_id']], 'commodity_id');
            $current = $this->getValue('product_stock', ['product_id' => $v['product_id']], 'stock');
            $price = $this->getValue('commodity', ['id' => $dan], 'purchase_price');
            $rel['product_id'] = $v['product_id'];
            $rel['pid'] = $id;
            $rel['put_number'] = $v['put_number'];
            $rel['front'] =isset($current) ? $current : 0;
            if ($current - $v['put_number'] > 0) {
                $rel['loss_num'] = $current - $v['put_number'];
                $rel['loss_price'] = $rel['loss_num'] * $price;
                $rel['state'] = '盘盈';
            } else if ($current - $v['put_number'] == 0) {
                $rel['loss_num'] = 0;
                $rel['loss_price'] = 0.00;
                $rel['state'] = '正常';
            } else {
                $rel['loss_num'] = '-' . $v['put_number'] - $current;
                $rel['loss_price'] = '-' . $rel['loss_num'] * $price;
                $rel['state'] = '盘亏';
            }
            $this->getAdd('inventory_relation',$rel);
        }
        return 1;
    }
}